package team3.tracking.communication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;


public class TrackingServerPC implements UDPServerAdapter{
	//only using UDP for now, no TCP code yet
	
	
	/* Pose class stores the client data */
	
	private int numberOfThreads;
	private int port;
	private ThreadPool threadPool;	
	FileManagement fileManagement;
	private boolean status=false;
	public TrackingServerPC(){
				int option = 0;
				do {	
				try {
				option = Menu();	
				switch(option){
				case 1:
					if(status==false)
					{
					fileManagement= new FileManagement();
					numberOfThreads = 10;
			        threadPool = new ThreadPool(numberOfThreads);
			        port = 6000;//8080;
			         System.out.println("Calling Create File");
			        fileManagement.CreateFile();
					UDPServerHandler mUDPServerHandler = new UDPServerHandler(this,threadPool,port);
					mUDPServerHandler.start();
			        System.out.println("Server working");
					@SuppressWarnings("unused")
					TCPServerHandler mTCPServerHandler = new  TCPServerHandler(threadPool ,fileManagement);
					status=true;
					}
				break;
				case 2:
				if(status==true)
				{
					fileManagement.CloseFile();		
					status=false;
				}
				break;
				case 3:
					if(status==true)
					{
						fileManagement.CloseFile();					
					}
				System.out.println("Server is shutting down.");
				System.exit(0);
				break;
				default: System.out.println("Option incorrect.");
				break;
				} 
				}catch (IOException e) {
				e.printStackTrace();
				}

				}while (option != 3);			
			}
	
	public static void main(String[] args) {
		
		
		new TrackingServerPC();
		
	}
	public static int Menu() throws IOException{ 

		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		int op=0;
		System.out.println
		("================ Server Menu =============\n"+
		"1. Start Server"+"\n"+
		"2. Stop Server"+"\n"+
		"3. Exit"+"\n"+
		"=============================================="+"\n");
		op=Integer.parseInt(in.readLine());
		return (op);
		}

	@SuppressWarnings("static-access")
	@Override
	public void onUDPDataReceived(byte[] data, int dataLength) {

		ClientData cData=PositionInfo.deserializeData(new String (data ));
		cData.setServerTimeStamp(new Date().getTime());
		System.out.println("Inside TrackingServerPc");
		System.out.println(new Date().getTime());
		System.out.println(cData.getServerTimeStamp());
		
		PositionInfo.setPositionInfo(cData);		
		
		fileManagement.WriteFile(cData);
    	
	}
	

}
